#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
イベント処理

"""

import context
import re
import codecs
import util
import win32clipboard
import win32con
import thread
import threading
import ctypes
import ctypes.wintypes
import time

user32 = ctypes.windll.user32

ASFW_ANY = -1
LSFW_LOCK = 1
LSFW_UNLOCK = 2
WS_EX_LAYERED = 0x80000
LWA_ALPHA = 2

"""
カウント
"""
class Count:
    
    def __init__(self):
        context.Count = self
        self.counter = {}
        self.target = context.UI
        self.template = context.Config["template"]
        self.resetCount()
            
        
    def resetOne(self, value):
            if(value["type"]=="int"):
                self.counter[value["str"]] = 0
                try:
                    context.UI.builder.ctrl[value["str"]].SetValue(0)
                except Exception:
                    pass
            else:
                self.counter[value["str"]] = util.decode(u"×")
                try:
                    context.UI.builder.ctrl[value["str"]].SetValue(False)
                except Exception:
                    pass
        
    def initResult(self):
        result = self.template  
        for key, v in self.counter.iteritems():
            
            p = re.compile(key)
            result = p.sub(v.__str__(), result)
        self.target.result_text.SetValue(util.encode(result))
        self.target.copyText(self)
        
    def resetCount(self):
        for value in context.Config["target"]:
            self.resetOne(value)

            
        self.initResult()

"""
計算
"""
class Counter:
    def __init__(self, count, str, value):
        self.count = count
        self.counter = count.counter
        self.str = str
        self.value = value
        
        
    def calc(self, event):
        
        if(self.str == "+"):
            self.addPlusEvent(self.value)
        else:
            self.addMinusEvent(self.value)
            
    def calcSpin(self, evt):
        if(self.value["type"]=="int"):
            self.counter[self.value["str"]] = evt.GetInt()
        else:
            if(evt.GetInt()==1):
                self.counter[self.value["str"]] = util.decode(u"○")
            else:
                self.counter[self.value["str"]] = util.decode(u"×")
        
        self.count.initResult()
        
    def addPlusEvent(self, v):
        
        try:
            if(v["max"] == self.counter[v["str"]]):
                return
        except Exception:
            pass
        
        if(v["type"]=="bool"):
            self.counter[v["str"]]=1
        else:
            self.counter[v["str"]]=self.counter[v["str"]]+1
            try:
                self.counter[v["sum"]]=self.counter[v["sum"]]+1
            except Exception:
                pass
            
        self.count.initResult()
    
    def addMinusEvent(self, v):

        
        if(v["type"]=="bool"):
            self.minus(v["str"])
            self.count.initResult()
            return
        
        self.minus(v["str"])
        try:
            if(v["sum"] <= v["str"]):
                self.minus(v["sum"])
        except Exception:
            pass
        self.count.initResult()
            
    def minus(self, key):
        if(self.counter[key] > 0 ):
            self.counter[key]=self.counter[key]-1
    
            

"""
結果テキストの編集
"""
class ResultText:
    """
    クリップボードにセット
    """
    def setClipBoard(self):
        
        text = codecs.encode(context.UI.result_text.GetValue(), "sjis")
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardText(text)
        win32clipboard.CloseClipboard()
        print(text)
    
    
"""
ウィンドウ操作
"""    
def windowInit():
    
    win = WindowController()
    
    while(True):
        time.sleep(0.1)
        try:
            if(context.UI.isActive() != True):
                continue
        except Exception:
            continue
        
        (x, y) = context.UI.GetPosition()
        (w, h) = context.UI.GetSize()
        pt = ctypes.wintypes.POINT()
        user32.GetCursorPos(ctypes.byref(pt))
        
        if( pt.x >= x and pt.y >= y and pt.x <= x+w and pt.y <= y+h ):

            win.setName(context.UI.GetTitle().__str__())
            win.setActiveByName()
            
        else:
            win.setName("Fantasy Earth Zero")
            win.setActiveByName()
        
        
        
    
    
class WindowController:
    
    def __init__(self):
        self.name = ""
    """
    ウィンドウ名のセット
    """
    def setName(self, name):
        self.name = name
    
    def setAlpha(self, alpha):
        myHandle = user32.FindWindowA(None, self.name)
        exStyle = user32.GetWindowLongA(myHandle, win32con.GWL_EXSTYLE)
        user32.SetWindowLongA( myHandle, win32con.GWL_EXSTYLE, exStyle | WS_EX_LAYERED )
        user32.SetLayeredWindowAttributes(myHandle, 0, (255*alpha)/100, LWA_ALPHA)
    
    
    def setActiveByName(self):
        myHandle = user32.FindWindowA(None, self.name)
        self.setActive(myHandle)
        
    def setActive(self, myHandle):
        
        target_id = user32.GetWindowThreadProcessId(myHandle, None)
        active_id = user32.GetWindowThreadProcessId(user32.GetForegroundWindow(), None)
        user32.AttachThreadInput(target_id, active_id, True );
        user32.SetForegroundWindow(myHandle)
        user32.SetActiveWindow(myHandle)


